package org.onion.pattern.kit.validation;

import org.apache.commons.lang3.reflect.FieldUtils;

import java.lang.reflect.Field;

/**
 * 反射工具
 *
 */
final class ReflectUtils {

    private ReflectUtils() {
    }

    static Field getTargetField(Class<?> targetClass, String fieldName) {
        Field field;

        try {
            if (targetClass == null) {
                return null;
            }

            if (Object.class.equals(targetClass)) {
                return null;
            }

            field = FieldUtils.getDeclaredField(targetClass, fieldName, true);
            if (field == null) {
                field = getTargetField(targetClass.getSuperclass(), fieldName);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return field;
    }

    static void setFieldValue(Object obj, String fieldName, Object value) {
        if (null == obj) {
            return;
        }
        Field targetField = getTargetField(obj.getClass(), fieldName);
        if (targetField == null) {
            return;
        }

        try {
            FieldUtils.writeField(targetField, obj, value);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }


}
